{% extends "base.html" %}

{% block title %}知识库管理 - 乳腺癌预测系统{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h4 class="mb-0">
                        <i class="fas fa-database"></i> 知识库管理
                    </h4>
                    <small>管理RAG系统的医学知识库</small>
                </div>
                <div class="card-body">
                    <!-- 统计信息 -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="card bg-primary text-white">
                                <div class="card-body text-center">
                                    <h5 id="total-knowledge">-</h5>
                                    <small>总知识数</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-info text-white">
                                <div class="card-body text-center">
                                    <h5 id="total-categories">-</h5>
                                    <small>知识分类</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card bg-light">
                                <div class="card-body">
                                    <h6>分类统计</h6>
                                    <div id="category-stats"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <button class="btn btn-success" data-toggle="modal" data-target="#addKnowledgeModal">
                                <i class="fas fa-plus"></i> 添加新知识
                            </button>
                            <button class="btn btn-info" onclick="refreshStats()">
                                <i class="fas fa-sync"></i> 刷新统计
                            </button>
                        </div>
                        <div class="col-md-6">
                            <div class="input-group">
                                <input type="text" id="search-knowledge" class="form-control" placeholder="搜索知识...">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-primary" onclick="searchKnowledge()">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 知识列表 -->
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>标题</th>
                                    <th>分类</th>
                                    <th>内容预览</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="knowledge-table">
                                <tr>
                                    <td colspan="5" class="text-center">
                                        <div class="spinner-border" role="status">
                                            <span class="sr-only">加载中...</span>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加知识模态框 -->
<div class="modal fade" id="addKnowledgeModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加新知识</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="addKnowledgeForm">
                    <div class="form-group">
                        <label for="knowledge-title">标题</label>
                        <input type="text" class="form-control" id="knowledge-title" required>
                    </div>
                    <div class="form-group">
                        <label for="knowledge-category">分类</label>
                        <select class="form-control" id="knowledge-category">
                            <option value="基础概念">基础概念</option>
                            <option value="症状">症状</option>
                            <option value="诊断">诊断</option>
                            <option value="分期">分期</option>
                            <option value="治疗">治疗</option>
                            <option value="预防">预防</option>
                            <option value="预后">预后</option>
                            <option value="分子分型">分子分型</option>
                            <option value="筛查">筛查</option>
                            <option value="遗传">遗传</option>
                            <option value="危险因素">危险因素</option>
                            <option value="术后护理">术后护理</option>
                            <option value="化疗">化疗</option>
                            <option value="内分泌治疗">内分泌治疗</option>
                            <option value="靶向治疗">靶向治疗</option>
                            <option value="免疫治疗">免疫治疗</option>
                            <option value="复发转移">复发转移</option>
                            <option value="心理支持">心理支持</option>
                            <option value="营养支持">营养支持</option>
                            <option value="康复锻炼">康复锻炼</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="knowledge-content">内容</label>
                        <textarea class="form-control" id="knowledge-content" rows="8" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" onclick="addKnowledge()">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑知识模态框 -->
<div class="modal fade" id="editKnowledgeModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑知识</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editKnowledgeForm">
                    <input type="hidden" id="edit-knowledge-id">
                    <div class="form-group">
                        <label for="edit-knowledge-title">标题</label>
                        <input type="text" class="form-control" id="edit-knowledge-title" required>
                    </div>
                    <div class="form-group">
                        <label for="edit-knowledge-category">分类</label>
                        <select class="form-control" id="edit-knowledge-category">
                            <option value="基础概念">基础概念</option>
                            <option value="症状">症状</option>
                            <option value="诊断">诊断</option>
                            <option value="分期">分期</option>
                            <option value="治疗">治疗</option>
                            <option value="预防">预防</option>
                            <option value="预后">预后</option>
                            <option value="分子分型">分子分型</option>
                            <option value="筛查">筛查</option>
                            <option value="遗传">遗传</option>
                            <option value="危险因素">危险因素</option>
                            <option value="术后护理">术后护理</option>
                            <option value="化疗">化疗</option>
                            <option value="内分泌治疗">内分泌治疗</option>
                            <option value="靶向治疗">靶向治疗</option>
                            <option value="免疫治疗">免疫治疗</option>
                            <option value="复发转移">复发转移</option>
                            <option value="心理支持">心理支持</option>
                            <option value="营养支持">营养支持</option>
                            <option value="康复锻炼">康复锻炼</option>
                            <option value="其他">其他</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="edit-knowledge-content">内容</label>
                        <textarea class="form-control" id="edit-knowledge-content" rows="8" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateKnowledge()">更新</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    loadKnowledgeStats();
    loadAllKnowledge();
});

function loadKnowledgeStats() {
    fetch('/api/rag/stats')
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            console.error('加载统计信息失败:', data.error);
            return;
        }
        
        document.getElementById('total-knowledge').textContent = data.total_knowledge;
        document.getElementById('total-categories').textContent = data.total_categories;
        
        // 显示分类统计
        let categoryStatsHtml = '';
        for (const [category, count] of Object.entries(data.category_counts)) {
            categoryStatsHtml += `<span class="badge badge-secondary mr-1">${category}: ${count}</span>`;
        }
        document.getElementById('category-stats').innerHTML = categoryStatsHtml;
    })
    .catch(error => {
        console.error('Error:', error);
    });
}

function loadAllKnowledge() {
    fetch('/api/rag/categories')
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            document.getElementById('knowledge-table').innerHTML = 
                '<tr><td colspan="5" class="text-center text-danger">加载失败: ' + data.error + '</td></tr>';
            return;
        }
        
        // 加载所有分类的知识
        const promises = data.categories.map(category => 
            fetch(`/api/rag/knowledge/${encodeURIComponent(category)}`)
            .then(response => response.json())
        );
        
        Promise.all(promises)
        .then(responses => {
            let allKnowledge = [];
            responses.forEach(response => {
                if (response.knowledge) {
                    allKnowledge = allKnowledge.concat(response.knowledge);
                }
            });
            
            displayKnowledgeTable(allKnowledge);
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('knowledge-table').innerHTML = 
                '<tr><td colspan="5" class="text-center text-danger">加载失败，请稍后重试</td></tr>';
        });
    })
    .catch(error => {
        console.error('Error:', error);
    });
}

function displayKnowledgeTable(knowledge) {
    let html = '';
    knowledge.forEach(item => {
        const contentPreview = item.content.length > 100 ? 
            item.content.substring(0, 100) + '...' : item.content;
        
        html += `
            <tr>
                <td>${item.id}</td>
                <td>${item.title}</td>
                <td><span class="badge badge-info">${item.category}</span></td>
                <td>${contentPreview}</td>
                <td>
                    <button class="btn btn-sm btn-primary" onclick="editKnowledge(${item.id}, '${item.title}', '${item.category}', '${item.content.replace(/'/g, "\\'")}')">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteKnowledge(${item.id})">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </td>
            </tr>
        `;
    });
    
    document.getElementById('knowledge-table').innerHTML = html;
}

function addKnowledge() {
    const title = document.getElementById('knowledge-title').value.trim();
    const category = document.getElementById('knowledge-category').value;
    const content = document.getElementById('knowledge-content').value.trim();
    
    if (!title || !content) {
        alert('请填写标题和内容');
        return;
    }
    
    fetch('/api/rag/add-knowledge', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            title: title,
            category: category,
            content: content
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('添加失败: ' + data.error);
        } else {
            alert('添加成功');
            $('#addKnowledgeModal').modal('hide');
            document.getElementById('addKnowledgeForm').reset();
            loadKnowledgeStats();
            loadAllKnowledge();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('添加失败，请稍后重试');
    });
}

function editKnowledge(id, title, category, content) {
    document.getElementById('edit-knowledge-id').value = id;
    document.getElementById('edit-knowledge-title').value = title;
    document.getElementById('edit-knowledge-category').value = category;
    document.getElementById('edit-knowledge-content').value = content;
    $('#editKnowledgeModal').modal('show');
}

function updateKnowledge() {
    const id = document.getElementById('edit-knowledge-id').value;
    const title = document.getElementById('edit-knowledge-title').value.trim();
    const category = document.getElementById('edit-knowledge-category').value;
    const content = document.getElementById('edit-knowledge-content').value.trim();
    
    if (!title || !content) {
        alert('请填写标题和内容');
        return;
    }
    
    fetch('/api/rag/update-knowledge', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            id: parseInt(id),
            title: title,
            category: category,
            content: content
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('更新失败: ' + data.error);
        } else {
            alert('更新成功');
            $('#editKnowledgeModal').modal('hide');
            loadKnowledgeStats();
            loadAllKnowledge();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('更新失败，请稍后重试');
    });
}

function deleteKnowledge(id) {
    if (!confirm('确定要删除这条知识吗？此操作不可撤销。')) {
        return;
    }
    
    fetch('/api/rag/delete-knowledge', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            id: id
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('删除失败: ' + data.error);
        } else {
            alert('删除成功');
            loadKnowledgeStats();
            loadAllKnowledge();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('删除失败，请稍后重试');
    });
}

function refreshStats() {
    loadKnowledgeStats();
    loadAllKnowledge();
}

function searchKnowledge() {
    const query = document.getElementById('search-knowledge').value.trim();
    if (!query) {
        loadAllKnowledge();
        return;
    }
    
    fetch('/api/rag/search', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            query: query,
            top_k: 50
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('搜索失败: ' + data.error);
        } else {
            displayKnowledgeTable(data.results);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('搜索失败，请稍后重试');
    });
}
</script>
{% endblock %}
